/*
 * Copyright (c) 2006-2021, Halo team
 *
 * SPDX-License-Identifier: GPLv3
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-09-11     Eywen        the first version
 */

#include "fdm_printer.h"
#include "motion_step.h"
#include "endstop.h"
#include "extruder_step.h"
#include "heater.h"
#include "temperature.h"
#include "drivers/hwtimer.h"
#include "heater.h"
#include "hard_task.h"
#include "motion_control.h"

static temperature_t s_temperature_ntc;               /* ntc温度传感器 */

/* 定时器超时回调函数 */
#if (defined SOC_AB32VG1)
RT_SECTION(".irq.timer")
#endif
static rt_err_t step_run_schdule(rt_device_t dev, rt_size_t size)
{
    extern motion_control_t *motion_control;
    if((motion_control->motion_step_z.ops->is_motion(&(motion_control->motion_step_z)) == true) ||
            (ringbuff_is_empty(motion_control->motion_step_z.step_drv->pulse_list) == false)){
        motion_control->motion_step_z.step_drv->ops-> \
                        timer_schdule(motion_control->motion_step_z.step_drv);

        return RT_EOK;
    }

    motion_control->motion_step_x.step_drv->ops-> \
            timer_schdule(motion_control->motion_step_x.step_drv);
    motion_control->motion_step_y.step_drv->ops-> \
            timer_schdule(motion_control->motion_step_y.step_drv);
    motion_control->motion_step_y_1.step_drv->ops-> \
                timer_schdule(motion_control->motion_step_y_1.step_drv);

    return RT_EOK;
}


/* 初始化挤出机 */
void fdm_extruder_init(void)
{
    if(false == temperature_register(&s_temperature_ntc, temperature_type_ntc)){
        return;
    }

    /* 初始化传感器接口 */
    if(false == temperature_init(&s_temperature_ntc,            /* 描述符 */
                                 TEMPERATURE_NTC_ADC_DEV_NAME,  /* 驱动名称 */
                                 TEMPERATURE_NTC_ADC_DEV_CHANNEL, /* 通道号 */
                                 12,                            /* adc精度 */
                                 ntc_mode_zm_1460,              /* ntc传感器型号 */
                                 4700)){                        /* 上拉电阻阻值 */

    }
}

void fdm_printer_test(void)
{
    /* 初始化所有的温度传感器 */
    //fdm_extruder_init();

    rt_pin_mode(49, PIN_MODE_OUTPUT);
    rt_pin_write(49, PIN_HIGH);

#if 0
    heater_t *heater;
    heater = heater_create(pid_type_position);
    /* 设置pid的三个参数，输出最大、最小值 */
    heater->pid->ops->init(heater->pid, 0.5, 0.5, 1, 100, 0);
    /* 设置调节的目标值 */
    heater->pid->ops->target_set(heater->pid, 30);
    /* 绑定温度传感器，设置pid的计算周期 */
    heater->ops->init(heater, 1, true, 3000, &s_temperature_ntc);
    /* 开始软件定时器 */
    heater->ops->start(heater);
#endif
    hard_task_t *hard_task;
    /* 创建硬实时任务对象 */
    hard_task = hard_task_creater();

    hard_task->ops->init(hard_task, STEP_SCHDULE_HWTIMER_DEV_NAME,
                         STEP_SCHDULE_TIMER_FREQ);//
    hard_task->ops->set_run(hard_task, step_run_schdule);

    hard_task->ops->start(hard_task, STEP_SCHDULE_FREQ);
}
